package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.privilege.client.ApplicationClient;
import com.leyou.privilege.dto.ApplicationDTO;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.LambdaConversionException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AuthService {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private UserClient userClient;

    private static final String USER_ROLE = "role_user";

    public void login(String username, String password, HttpServletResponse response) {
        try {
            //查询用户
            UserDTO user = userClient.queryUserByUsernameAndPassword(username, password);
            //生成userInfo
            UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), USER_ROLE);
            //生成token
            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, prop.getPrivateKey(), prop.getUser().getExpire());
            //写入cookie
            WriteCookie(response, token);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
    }

    private void WriteCookie(HttpServletResponse response, String token) {
        CookieUtils.newCookieBuilder()
                .response(response)//response,用于写cookie
                .httpOnly(true)//保证安全防止xss攻击，不允许JS操作cookie
                .domain(prop.getUser().getCookieDomain())//设置domain
                .name(prop.getUser().getCookieName()).value(token)//设置cookie名称和值
                .build();//写cookie
    }

    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            //读取cookie
            String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
            //获取token信息
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            //获取token的id，校检黑名单
            String id = payload.getId();
            Boolean boo = redisTemplate.hasKey(id);
            if (boo !=null && boo){
                //抛出异常，证明token无效，直接返回401
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            //获取过期时间
            Date expiration = payload.getExpiration();
            //获取新的刷新时间
            DateTime refreshTime = new DateTime(expiration.getTime()).plusMinutes(prop.getUser().getMinRefreshInterval());
            //判断是否已经过了刷新时间
            if (refreshTime.isBefore(System.currentTimeMillis())){
                //如果过了刷新时间，则生成新token
                token = JwtUtils.generateTokenExpireInMinutes(payload.getUserInfo(), prop.getPrivateKey(), prop.getUser().getExpire());
                //写入cookie
                WriteCookie(response,token);
            }
            return payload.getUserInfo();
        } catch (Exception e) {
            log.error("用户信息认证失败",e);
            //抛出异常，证明token无效，直接返回401
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        //解析token
        Payload<Object> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
        //获取id和有效期剩余时长
        String id = payload.getId();
        long time = payload.getExpiration().getTime() - System.currentTimeMillis();
        //写入redis，剩余时间超过5秒以上才写
        if (time>5000){
            redisTemplate.opsForValue().set(id,"",time, TimeUnit.MILLISECONDS);
        }
        //删除cookie
        CookieUtils.deleteCookie(prop.getUser().getCookieName(),prop.getUser().getCookieDomain(),response);

    }

    @Autowired
    private ApplicationClient applicationClient;

    public String authenticate(Long id, String secret) {
        try {
            //校检id和secret是否正确
            ApplicationDTO appDTO = applicationClient.queryByAppIdAndSecret(id, secret);
            //生成JWT
            AppInfo appInfo = new AppInfo();
            appInfo.setId(appDTO.getId());
            appInfo.setServiceName(appDTO.getServiceName());
            return JwtUtils.generateTokenExpireInMinutes(appInfo,prop.getPrivateKey(),prop.getApp().getExpire());
        } catch (Exception e) {
            log.error("【授权中心】验证服务id和secret出错。",e);
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }
    }
}
